package com.yc.demo.d0801;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "ResMappingServlet",
        value = "/upload/*")
public class ResMappingServlet extends HttpServlet {

    public static final String UPLOAD_DIR = "D:\\_文件柜\\134\\0801";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 127.0.0.1/xxx/upload/a.jpg => D:\_文件柜\134\0801\a.jpg
        // 127.0.0.1/xxx/upload/a/b/a.jpg => D:\_文件柜\134\0801\a\b\a.jpg
        // 获取资源地址 => webPath
        String requestURI = request.getRequestURI();
        // 上下文对象
        final ServletContext servletContext = request.getServletContext();
        // 去除上下文路径
        final String contextPath = servletContext.getContextPath();
        requestURI = requestURI.substring(contextPath.length());
        // 去掉 upload
        String resPath = requestURI.substring("/upload".length());
        // 拼接 本地磁盘路径
        String diskPath = UPLOAD_DIR + resPath;
        // 获取文件类型
        String contentType = servletContext.getMimeType(resPath);
        response.setContentType(contentType);
        final ServletOutputStream out = response.getOutputStream();
        try (FileInputStream fis = new FileInputStream(diskPath)) {
            byte[] bytes = new byte[1024];
            int count;
            while ((count = fis.read(bytes)) > 0) {
                out.write(bytes, 0, count);
            }
        }
    }
}
